package com.xxx.servlet;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xxx.para.ParametersUtil;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import eu.bitwalker.useragentutils.Version;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Date: 2015-10-29
 * Time: 下午4:53
 *
 * @author Ming Lei
 * @version 1.0
 */
@Slf4j
public class HttpServletUtil {

    public static HttpServletRequest getHttpServletRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

    public static String getServiceHost(HttpServletRequest request) {
        return request.getLocalAddr() + ":" + request.getLocalPort();
    }

    public static String getRequestIp(HttpServletRequest httpServletRequest) {
        String ip = httpServletRequest.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("X-Real-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = httpServletRequest.getRemoteAddr();
        }
        return ip;
    }

    public static void init(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "Origin,Content-Type,Accept,token,X-Requested-With,X-USER-TOKEN,APP-LANG,TERMINAL,DEVICE_TYPE,VERSION,DEVICE_NUMBER");
        request.setAttribute("AUTH_START_TIME", System.currentTimeMillis());

        if(log.isInfoEnabled()){
            log.info(request.getRequestURL().toString());
            log.info( "ContentType: {}", request.getContentType());
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String parametNames = parameterNames.nextElement();
                log.info("参数" + parametNames + ":" + request.getParameter(parametNames));
            }
            log.info("ip:"+getRequestIp()+"|浏览器:"+getBrowser()+"|系统："+getOperatingSystem());
        }

    }
    
    public static String getRequestIp() {
        return getRequestIp(getHttpServletRequest());
    }

    /**
     * 先解析成Json，如果异常，解析为queryString格式的
     *
     * @param request
     * @return
     */
    public static String parseParameters(HttpServletRequest request) {
        String parameters = null;
        try {
            parameters = parseParametersToJson(request);
        } catch (JsonProcessingException e) {
            parameters = parseParametersToQueryString(request, parameters);
        }
        return parameters;
    }

    private static String parseParametersToQueryString(HttpServletRequest request, String parameters) {
        StringBuffer parametersBuffer = new StringBuffer("");
        Enumeration<String> parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String parameter = parameterNames.nextElement();
            if (!parameter.equals("password")) {
                parametersBuffer.append("&" + parameter + "=" + request.getParameter(parameter));
            } else {
                parametersBuffer.append("&password=cantLogUserPassword");
            }
        }
        if (parametersBuffer.length() > 0) {
            parameters = parametersBuffer.substring(1);
        }
        return parameters;
    }

    private static String parseParametersToJson(HttpServletRequest request) throws JsonProcessingException {
        String parameters = null;
        Map<String, String[]> parameterMap = request.getParameterMap();
        if (parameterMap.containsKey("password")) {
            Map<String, String[]> noPasswordMap = new LinkedHashMap<>();
            Enumeration<String> parameterNames = request.getParameterNames();
            while (parameterNames.hasMoreElements()) {
                String parameter = parameterNames.nextElement();
                if (!parameter.equals("password")) {
                    noPasswordMap.put(parameter, parameterMap.get(parameter));
                }
            }
            noPasswordMap.put("password", new String[]{"cant log user password!"});
            parameterMap = noPasswordMap;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        parameters = objectMapper.writeValueAsString(parameterMap);
        return parameters;
    }


    /**
     * description:获取浏览器版本号
     * @author: dove king
     * @date: 11:21 2018/5/3
     * @param:[request]
     * @return java.lang.String
     */
    public static  String getBrowser(){
        //获取浏览器信息
        Browser browser = getUserAgent().getBrowser();
        //获取浏览器版本号
        Version version =  getUserAgent().getBrowserVersion();
        String info = "";
        if(!ParametersUtil.isNull(version)){
            info = browser.getName() + "/" + version.getVersion();
        }
        if("".equals(info)){
            info="Robot";
        }
        return info;
    }

    /**
     * 获取请求系统信息
     * @return
     */
    public static String getOperatingSystem(){
        String info = "";
        OperatingSystem operatingSystem = getUserAgent().getOperatingSystem();
        if(OperatingSystem.UNKNOWN.equals(operatingSystem)){
            info="Robot";
        }else {
            info =  operatingSystem.getName() + "/" + operatingSystem.name() + "/" + operatingSystem.getDeviceType().getName() + "/" + operatingSystem.getGroup().getName() + "/" + operatingSystem.getManufacturer().name();
        }
        return 	info;
    }

    /**
     * @Author Flying
     * @Description  获取UserAgent
     * @Date 15:38 2019/4/16
     * @Param []
     * @return eu.bitwalker.useragentutils.UserAgent
     **/
    private static UserAgent getUserAgent(){
       return UserAgent.parseUserAgentString(getUserAgentStr());
    }

    /**
     * @Author Flying
     * @Description  获取UserAgent字符串
     * @Date 15:38 2019/4/16
     * @Param []
     * @return java.lang.String
     **/
    private static String getUserAgentStr(){
        return getHttpServletRequest().getHeader("User-Agent");
    }
    

}
